<template>
  <div class="dashboard-container">
    <!-- 欢迎横幅 -->
    <div class="welcome-banner">
      <div class="welcome-content">
        <h1 class="welcome-title">
          <el-icon class="welcome-icon"><DocumentChecked /></el-icon>
          欢迎使用法律文献检索系统
        </h1>
        <p class="welcome-subtitle">智能化法律文献管理与检索平台</p>
      </div>
    </div>
    
    <!-- 主要内容 -->
    <div class="dashboard-content">
        <!-- 基础统计卡片 -->
        <div class="stats-cards">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="6" :lg="6">
              <div class="stat-card users-card">
                <div class="stat-left">
                  <div class="stat-icon users">
                    <el-icon size="32"><User /></el-icon>
                  </div>
                </div>
                <div class="stat-right">
                  <div class="stat-value">{{ formatNumber(basicStats.totalUsers || 0) }}</div>
                  <div class="stat-label">总用户数</div>
                  <div class="stat-change positive">
                    <span class="change-icon">↗</span>
                    今日新增 {{ basicStats.todayNewUsers || 0 }}
                  </div>
                </div>
              </div>
            </el-col>
            
            <el-col :xs="24" :sm="12" :md="6" :lg="6">
              <div class="stat-card documents-card">
                <div class="stat-left">
                  <div class="stat-icon documents">
                    <el-icon size="32"><Document /></el-icon>
                  </div>
                </div>
                <div class="stat-right">
                  <div class="stat-value">{{ formatNumber(basicStats.totalDocuments || 0) }}</div>
                  <div class="stat-label">文档数量</div>
                  <div class="stat-change positive">
                    <span class="change-icon">↗</span>
                    今日新增 {{ basicStats.todayNewDocuments || 0 }}
                  </div>
                </div>
              </div>
            </el-col>
            
            <el-col :xs="24" :sm="12" :md="6" :lg="6">
              <div class="stat-card cases-card">
                <div class="stat-left">
                  <div class="stat-icon cases">
                    <el-icon size="32"><Files /></el-icon>
                  </div>
                </div>
                <div class="stat-right">
                  <div class="stat-value">{{ formatNumber(basicStats.totalCases || 0) }}</div>
                  <div class="stat-label">案例数量</div>
                  <div class="stat-change info">
                    <span class="change-icon">♥</span>
                    收藏 {{ formatNumber(basicStats.totalFavorites || 0) }}
                  </div>
                </div>
              </div>
            </el-col>
            
            <el-col :xs="24" :sm="12" :md="6" :lg="6">
              <div class="stat-card comments-card">
                <div class="stat-left">
                  <div class="stat-icon comments">
                    <el-icon size="32"><ChatDotRound /></el-icon>
                  </div>
                </div>
                <div class="stat-right">
                  <div class="stat-value">{{ formatNumber(basicStats.totalComments || 0) }}</div>
                  <div class="stat-label">评论数量</div>
                  <div class="stat-change positive">
                    <span class="change-icon">↗</span>
                    今日新增 {{ basicStats.todayNewComments || 0 }}
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 图表区域 -->
        <div class="charts-section">
          <el-row :gutter="20">
            <!-- 搜索趋势图 -->
            <el-col :xs="24" :sm="24" :md="12" :lg="14">
              <div class="chart-card">
                <div class="chart-header">
                  <h3>搜索趋势（最近7天）</h3>
                </div>
                <div class="chart-content">
                  <div 
                    ref="searchTrendChart"
                    v-if="searchTrendData.dates.length > 0"
                    style="height: 300px;"
                  ></div>
                  <div v-else class="loading-placeholder">加载中...</div>
                </div>
              </div>
            </el-col>

            <!-- 文档类型分布饼图 -->
            <el-col :xs="24" :sm="24" :md="12" :lg="10">
              <div class="chart-card">
                <div class="chart-header">
                  <h3>文档类型分布</h3>
                </div>
                <div class="chart-content">
                  <div 
                    ref="documentTypeChart"
                    v-if="documentTypeData.length > 0"
                    style="height: 300px;"
                  ></div>
                  <div v-else class="loading-placeholder">加载中...</div>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { User, Document, Files, ChatDotRound, DocumentChecked } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { getBasicStatistics, getSearchTrendData, getDocumentTypeChart } from '../api/statistics'

// 图表引用
const searchTrendChart = ref(null)
const documentTypeChart = ref(null)
let searchTrendChartInstance = null
let documentTypeChartInstance = null

// 基础统计数据
const basicStats = reactive({
  totalUsers: 0,
  totalDocuments: 0,
  totalCases: 0,
  totalComments: 0,
  totalFavorites: 0,
  todayNewUsers: 0,
  todayNewDocuments: 0,
  todayNewComments: 0
})

// 搜索趋势数据
const searchTrendData = reactive({
  dates: [],
  counts: []
})

// 文档类型数据
const documentTypeData = ref([])

// 初始化搜索趋势图表
const initSearchTrendChart = () => {
  if (searchTrendChart.value && searchTrendData.dates.length > 0) {
    searchTrendChartInstance = echarts.init(searchTrendChart.value)
    const option = {
      title: {
        text: '最近7天搜索趋势',
        left: 'center',
        textStyle: {
          fontSize: 14
        }
      },
      tooltip: {
        trigger: 'axis',
        formatter: '{b}<br/>{a}: {c} 次'
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: searchTrendData.dates,
        axisLabel: {
          fontSize: 12
        }
      },
      yAxis: {
        type: 'value',
        name: '搜索次数',
        axisLabel: {
          fontSize: 12
        }
      },
      series: [{
        name: '搜索次数',
        type: 'line',
        data: searchTrendData.counts,
        smooth: true,
        lineStyle: {
          color: '#67C23A',
          width: 3
        },
        itemStyle: {
          color: '#67C23A'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0, y: 0, x2: 0, y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(103, 194, 58, 0.3)' },
              { offset: 1, color: 'rgba(103, 194, 58, 0.05)' }
            ]
          }
        }
      }]
    }
    searchTrendChartInstance.setOption(option)
  }
}

// 初始化文档类型图表
const initDocumentTypeChart = () => {
  if (documentTypeChart.value && documentTypeData.value.length > 0) {
    documentTypeChartInstance = echarts.init(documentTypeChart.value)
    const option = {
      title: {
        text: '文档类型分布',
        left: 'center',
        textStyle: {
          fontSize: 14
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        bottom: 20
      },
      series: [{
        name: '文档类型',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['60%', '50%'],
        data: documentTypeData.value,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }]
    }
    documentTypeChartInstance.setOption(option)
  }
}

// 获取基础统计数据
const fetchBasicStats = async () => {
  try {
    const response = await getBasicStatistics()
    if (response.code === 200) {
      Object.assign(basicStats, response.data)
    }
  } catch (error) {
    console.error('获取基础统计数据失败:', error)
  }
}

// 获取搜索趋势数据
const fetchSearchTrend = async () => {
  try {
    const response = await getSearchTrendData()
    if (response.code === 200) {
      searchTrendData.dates = response.data.dates
      searchTrendData.counts = response.data.counts
      // 等待DOM更新后初始化图表
      nextTick(() => {
        initSearchTrendChart()
      })
    }
  } catch (error) {
    console.error('获取搜索趋势数据失败:', error)
  }
}

// 获取文档类型分布数据
const fetchDocumentTypeData = async () => {
  try {
    const response = await getDocumentTypeChart()
    if (response.code === 200) {
      documentTypeData.value = response.data.items
      // 等待DOM更新后初始化图表
      nextTick(() => {
        initDocumentTypeChart()
      })
    }
  } catch (error) {
    console.error('获取文档类型数据失败:', error)
  }
}

// 数字格式化函数
const formatNumber = (num) => {
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + 'w'
  } else if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'k'
  }
  return num.toString()
}

// 页面加载时获取所有数据
onMounted(() => {
  fetchBasicStats()
  fetchSearchTrend()
  fetchDocumentTypeData()
})
</script>

<style scoped>
.dashboard-container {
  padding: 0;
  background-color: #f5f7fa;
  min-height: 100vh;
  width: 100%;
  overflow-x: hidden;
}

/* 欢迎横幅样式 */
.welcome-banner {
  background: linear-gradient(135deg, #7367F0 0%, #9b87ff 50%, #b3a7ff 100%);
  color: white;
  padding: 40px 20px;
  margin-bottom: 0;
  position: relative;
  overflow: hidden;
}

.welcome-banner::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="50" cy="50" r="1" fill="rgba(255,255,255,0.1)"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
  opacity: 0.1;
}

.welcome-content {
  text-align: center;
  position: relative;
  z-index: 1;
  max-width: 800px;
  margin: 0 auto;
}

.welcome-title {
  font-size: 36px;
  font-weight: 700;
  margin: 0 0 15px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 15px;
  text-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.welcome-icon {
  font-size: 40px;
  color: rgba(255, 255, 255, 0.95);
}

.welcome-subtitle {
  font-size: 18px;
  margin: 0;
  opacity: 0.9;
  font-weight: 300;
  letter-spacing: 1px;
}

.dashboard-content {
  padding: 30px 20px 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.stats-cards {
  margin-bottom: 25px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 25px;
  display: flex;
  align-items: center;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  height: 120px;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
}

.stat-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, var(--card-color-start), var(--card-color-end));
}

.users-card {
  --card-color-start: #667eea;
  --card-color-end: #764ba2;
}

.documents-card {
  --card-color-start: #f093fb;
  --card-color-end: #f5576c;
}

.cases-card {
  --card-color-start: #4facfe;
  --card-color-end: #00f2fe;
}

.comments-card {
  --card-color-start: #43e97b;
  --card-color-end: #38f9d7;
}

.stat-left {
  margin-right: 20px;
}

.stat-icon {
  width: 70px;
  height: 70px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  background: linear-gradient(135deg, var(--card-color-start), var(--card-color-end));
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
}

.stat-right {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.stat-value {
  font-size: 32px;
  font-weight: 700;
  color: #2c3e50;
  margin-bottom: 5px;
  line-height: 1;
}

.stat-label {
  font-size: 15px;
  color: #7f8c8d;
  margin-bottom: 8px;
  font-weight: 500;
}

.stat-change {
  font-size: 13px;
  display: flex;
  align-items: center;
  font-weight: 500;
}

.stat-change.positive {
  color: #27ae60;
}

.stat-change.info {
  color: #e74c3c;
}

.change-icon {
  margin-right: 5px;
  font-weight: bold;
  font-size: 14px;
}

.charts-section {
  margin-top: 20px;
}

.chart-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  height: 400px;
}

.chart-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.chart-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.chart-content {
  height: calc(100% - 60px);
}

.loading-placeholder {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .dashboard-content {
    padding: 15px;
  }
  
  .stat-card {
    padding: 20px;
    height: 100px;
    margin-bottom: 15px;
  }
  
  .stat-icon {
    width: 55px;
    height: 55px;
    margin-right: 15px;
  }
  
  .stat-value {
    font-size: 24px;
  }
  
  .stat-label {
    font-size: 13px;
  }
  
  .stat-change {
    font-size: 11px;
  }
  
  .chart-card {
    padding: 15px;
    height: 350px;
  }
}

@media (max-width: 480px) {
  .stat-card {
    padding: 15px;
    height: 90px;
  }
  
  .stat-icon {
    width: 50px;
    height: 50px;
    margin-right: 12px;
  }
  
  .stat-value {
    font-size: 20px;
  }
  
  .stat-label {
    font-size: 12px;
  }
  
  .stat-change {
    font-size: 10px;
  }
  
  .welcome-title {
    font-size: 24px;
    flex-direction: column;
    gap: 10px;
  }
  
  .welcome-icon {
    font-size: 32px;
  }
  
  .welcome-subtitle {
    font-size: 14px;
  }
  
  .welcome-banner {
    padding: 30px 15px;
  }
}
</style>
